package genetic.q2;

import java.util.Arrays;


public class TSPGenotype implements PuzzleGenotype{

	int[] rep;
	double[] aid;
	TSPGraph graph;


	public TSPGenotype(int[] rep, TSPGraph g){
		this.rep = rep;
		this.graph = g;
		this.aid = new double[rep.length];
		for(int i=0;i<aid.length;i++){
			aid[i]=0;
		}
	}

	@Override
	public PuzzleGenotype clone(){
		return new TSPGenotype(Arrays.copyOf(rep, rep.length), graph);
	}

	public int[] getIntString() {
		return rep;
	}

	@Override
	public String toString() {
		int length = graph.getDistance(rep[0]-1, rep[rep.length-1]-1);
		for (int i=0; i<rep.length-1; i++){
			length = length + graph.getDistance(rep[i]-1, rep[i+1]-1);
		}
		return "Distance " + length + ": " + Arrays.toString(rep);
	}

	public boolean travels(double[] t) {
		for(int i=0; i<rep.length;i++){
			if(rep[i]==t[0]){
				boolean flag=true;
				int eq=1;
				int plus=1;
				while(flag && plus < t.length-1){
					if(rep[(i+plus)%rep.length]==t[plus]){
						plus++;
						eq++;
					}else flag=false;
				}
				if(eq==t.length-1)
					return true;
				else break;
			}
		}
		return false;
	}

	public int[] getPrePost(double[] b) {
		int[] ans = new int[2];
		for(int i=0; i<rep.length;i++){
			if(rep[i]==b[0]){
				ans[0]=rep[((i-1)+rep.length)%rep.length];
				ans[1]=rep[(i+b.length-1)%rep.length];
				return ans;
			}
		}
		return ans;
	}

	public int[] updateAid(double[] b) {
		int[] ans = new int[2];
		for(int i=0; i<rep.length;i++){
			if(rep[i]==b[0]){
				for(int j=0;j<b.length-1;j++){
					if(aid[(i+j)%aid.length]> b[b.length-1])
						aid[(i+j)%aid.length]=b[b.length-1];
				}
			}
		}
		return ans;
	}	

	@Override
	public double[] getAid() {
		return aid;
	}
}
